package me.caofeng.controller;

import me.caofeng.annotation.Authentication;
import me.caofeng.annotation.MediaType;
import me.caofeng.enums.MediaTypes;
import me.caofeng.enums.ResponseCode;
import me.caofeng.enums.Role;
import me.caofeng.pojo.FileForm;
import me.caofeng.pojo.Response;
import me.caofeng.service.api.IFileService;
import me.caofeng.util.Constant;
import me.caofeng.util.PropertiesUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

/**
 * Copyright © 2017曹峰. All rights reserved.
 *
 * @Prject: mall
 * @Package: me.caofeng.controller
 * @Description: 文件上传
 * @Author: 曹峰 blog.caofeng.me
 * @Date: 2017-06-21 11:01
 * @Version: V1.0
 */
@Controller
@RequestMapping(value = "file")
public class FileUploadController {
    private static Logger LOGGER = LogManager.getLogger(FileUploadController.class);

    @Autowired
    private IFileService fileService;

    @RequestMapping(value = "image/product", method = RequestMethod.POST)
    @MediaType(MediaTypes.IMAGE)
    @ResponseBody
    @Authentication(role = Role.ADMIN)
    public Response<List<String>> uploadImage(@Valid FileForm fileForm, BindingResult result) {
        Optional<ObjectError> error = result.getAllErrors()
                .stream().filter(objectError -> null != objectError).findFirst();

        if (error.isPresent()) {
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT, error.get().getDefaultMessage(), null);
        }

        return fileService.saveFile(fileForm.getFile(), Constant.PRODUCT_PATH,
                PropertiesUtil.getProperty(Constant.IMAGE_PRODUCT,Constant.IMAGE_PRODUCT_PATH));

    }


}
